package com.hdjk.view.activity.investment;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.IdRes;
import android.text.TextUtils;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.AdapterView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.hdjk.view.R;
import com.hdjk.view.activity.financial.FundDetailActivity;
import com.hdjk.view.activity.personalcenter.OpenAccountActivity;
import com.hdjk.view.adapter.GroupFundListAdapter;
import com.hdjk.view.callback.CallBackListener;
import com.hdjk.view.dialog.MyAlertDialog;
import com.hdjk.view.entity.GroupEntity;
import com.hdjk.view.entity.Performance;
import com.hdjk.view.network.GroupNetWork;
import com.hdjk.view.util.StringAppUtil;
import com.hdjk.view.util.ToastUtils;
import com.hdjk.view.util.UserTokenUtil;
import com.lst.projectlib.base.BaseActivity;
import com.lst.projectlib.entity.Msg;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by sxy on 2017/11/17.
 */

public class GroupDetailActivity extends BaseActivity implements View.OnClickListener, RadioGroup.OnCheckedChangeListener {
    private GroupEntity mGroup;
    private List<GroupEntity.PortfolioFund> mList;
    private GroupFundListAdapter mAdapter;
    private String code;
    // Content View Elements
    private com.lst.projectlib.component.CustomView.TopTitleBar ttb_title_bar;
    private TextView tv_name;
    private TextView tv_introduce;
    private TextView tv_daily_increases;
    private TextView tv_one_year;
    private RadioGroup rg_movements, rb_time;
    private RadioButton radio1, radio2, radio3, radio4;
    private WebView wv_chart;
    private com.lst.projectlib.component.ListView.ListViewForScrollView lv_data_list;
    private TextView tv_buy;
    private TextView tv_yifeng;
    // End Of Content View Elements
    private JSONObject perjson_month, perjson_3month, perjson_6month, perjson_year, perjson_3year, perjson_history;
    private JSONObject hsjson_year, hsjson_2year, hsjson_3year;

    private void bindViews() {
        ttb_title_bar = (com.lst.projectlib.component.CustomView.TopTitleBar) findViewById(R.id.ttb_title_bar);
        tv_name = (TextView) findViewById(R.id.tv_name);
        tv_introduce = (TextView) findViewById(R.id.tv_introduce);
        tv_daily_increases = (TextView) findViewById(R.id.tv_daily_increases);
        tv_one_year = (TextView) findViewById(R.id.tv_one_year);
        rg_movements = (RadioGroup) findViewById(R.id.rg_movements);
        rg_movements.setOnCheckedChangeListener(this);
        rb_time = (RadioGroup) findViewById(R.id.rb_time);
        rb_time.setOnCheckedChangeListener(this);
//        rb_earnings_movements = (RadioButton) findViewById(R.id.rb_earnings_movements);
//        rb_value_movements = (RadioButton) findViewById(R.id.rb_value_movements);
        radio1 = (RadioButton) findViewById(R.id.radio1);
        radio2 = (RadioButton) findViewById(R.id.radio2);
        radio3 = (RadioButton) findViewById(R.id.radio3);
        radio4 = (RadioButton) findViewById(R.id.radio4);
//        radio5 = (RadioButton) findViewById(R.id.radio5);
//        radio6 = (RadioButton) findViewById(R.id.radio6);
//        radio7 = (RadioButton) findViewById(R.id.radio7);
        wv_chart = (WebView) findViewById(R.id.wv_chart);
        lv_data_list = (com.lst.projectlib.component.ListView.ListViewForScrollView) findViewById(R.id.lv_data_list);
        tv_buy = (TextView) findViewById(R.id.tv_buy);
        tv_yifeng = (TextView) findViewById(R.id.tv_yifeng);
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        setContentView(R.layout.activity_group_detail);
        bindViews();
        ttb_title_bar.findViewById(R.id.tvNavBack).setOnClickListener(this);
        tv_yifeng.setOnClickListener(this);
        tv_buy.setBackgroundResource(R.color.black_999999);
    }

    @Override
    protected void initData() {
        initWebView();

        mAdapter = new GroupFundListAdapter(this);
        mList = new ArrayList<>();
        mAdapter.setDataList(mList);
        lv_data_list.setAdapter(mAdapter);
        lv_data_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                int index = (int) l;
                Intent intent = new Intent(GroupDetailActivity.this, FundDetailActivity.class);
                intent.putExtra("id", mList.get(index).getFundCode());
                intent.putExtra("type", FundDetailActivity.TYPE_FUND);
                startActivity(intent);
            }
        });
        code = getIntent().getStringExtra("code");
        if (!TextUtils.isEmpty(code)) {
            getGroupDetail(code);
        }
    }

    private void getGroupDetail(String code) {
        mDialog.show();
        JSONObject object = new JSONObject();
        try {
            object.put("portfolioCode", code);
            GroupNetWork.getGroupDetail(UserTokenUtil.getToken(GroupDetailActivity.this), object.toString(), new CallBackListener() {
                @Override
                public void onCallBackCompleted(Msg msg) {
                    mDialog.cancel();
                    if (msg != null && msg.getSuccess() && msg.getData() != null) {
                        mGroup = (GroupEntity) msg.getData();
                        setViews();
                    } else {
                    }
                }

                @Override
                public void onCallBackError(Msg msg) {
                    mDialog.cancel();
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private void getPerfromanceChart(JSONObject json, final String period) {
        try {
            if (wv_chart != null && null != json) {
                wv_chart.loadUrl("javascript:initChart('" + json.toString() + "')");
                return;
            }

            if (!mDialog.isShowing())
                mDialog.show();

            JSONObject object = new JSONObject();
            object.put("portfolioCode", code);
            object.put("period", period);

            GroupNetWork.getPortfolioPerfromance(UserTokenUtil.getToken(GroupDetailActivity.this), object.toString(), new CallBackListener() {
                @Override
                public void onCallBackCompleted(Msg msg) {
                    mDialog.dismiss();
                    if (msg != null && msg.getSuccess()) {
                        List<Performance> list = (List<Performance>) msg.getData();
                        showChart(period, list);
                    }
                }

                @Override
                public void onCallBackError(Msg msg) {
                    mDialog.cancel();
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private void showChart(String period, List<Performance> list) {
        if (list != null) {
            JSONObject jsonObject = new JSONObject();
            try {
                JSONArray legendArray = new JSONArray();
                JSONArray xDataArray = new JSONArray();
                JSONArray yDataArray = new JSONArray();
                JSONArray yDataArray1 = new JSONArray();

                legendArray.put(new JSONObject().put("legend", "组合收益(%)"));
                jsonObject.put("legend", legendArray);

                for (Performance performance : list) {
                    JSONObject xData = new JSONObject();
                    xData.put("time", performance.getNavDate());
                    JSONObject yData = new JSONObject();
                    yData.put("data", performance.getPerformance());

                    xDataArray.put(xData);
                    yDataArray1.put(yData);
                }
                yDataArray.put(yDataArray1);
                jsonObject.put("xData", xDataArray);
                jsonObject.put("yData", yDataArray);
                wv_chart.loadUrl("javascript:initChart('" + jsonObject.toString() + "')");
                if (period.equals("1")) {
                    perjson_month = jsonObject;
                } else if (period.equals("2")) {
                    perjson_3month = jsonObject;
                } else if (period.equals("3")) {
                    perjson_6month = jsonObject;
                } else if (period.equals("4")) {
                    perjson_year = jsonObject;
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }

    private void setViews() {
        if (mGroup != null) {
            tv_name.setText(mGroup.getPortfolioName());
            if (!TextUtils.isEmpty(mGroup.getPortfolioStrategy())) {
                String por=mGroup.getPortfolioStrategy();
                tv_introduce.setText(por.replace("奕丰",""));
            }
            if (!StringAppUtil.isEmptyOrNull(mGroup.getDay1Performance())) {
                tv_daily_increases.setText(mGroup.getDay1Performance() + "%");
            }
            if (!StringAppUtil.isEmptyOrNull(mGroup.getPerformance().getPerformanceYear1())) {
                BigDecimal b = new BigDecimal(mGroup.getPerformance().getPerformanceYear1());
                tv_one_year.setText(b.setScale(2, BigDecimal.ROUND_HALF_UP).toString() + "%");
            }
            mList.addAll(mGroup.getPortfolioFund());
            mAdapter.notifyDataSetChanged();
            tv_buy.setText("立即购买");
            tv_buy.setBackgroundResource(R.drawable.sure_button_selector);
            tv_buy.setOnClickListener(this);
        }
    }

    @SuppressLint("JavascriptInterface")
    private WebView initWebView() {
        wv_chart = (WebView) findViewById(R.id.wv_chart);
        WebSettings setting = wv_chart.getSettings();
        // 安全考虑
        // 密码不保存,默认会弹出对话框
        setting.setSavePassword(false);

        setting.setSupportZoom(true);//缩放开关
        setting.setBuiltInZoomControls(true);//设置是否可缩放
        setting.setDisplayZoomControls(false);

        //自适应屏幕
        setting.setUseWideViewPort(true);//设置webview推荐使用的窗口，设置为true，无限缩放，就需要使用大视图模式
        setting.setLoadWithOverviewMode(true);//设置webview加载的页面的模式，也设置为true。

        // 设置缓存
//		setting.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
        // 取消缓存
        setting.setCacheMode(WebSettings.LOAD_NO_CACHE);

        setting.setAllowFileAccess(true);
        setting.setAppCacheEnabled(true);
//        setting.setAllowUniversalAccessFromFileURLs(true);

        // 支持javascript
        setting.setJavaScriptEnabled(true);
        wv_chart.addJavascriptInterface(this, "javatojs");

        //最重要的方法，一定要设置数据缓存，这就是出不来的主要原因
        setting.setDomStorageEnabled(true);
        //启用数据库
        setting.setDatabaseEnabled(true);

        //启用地理定位
        setting.setGeolocationEnabled(true);
        String dir = this.getApplicationContext().getDir("database", Context.MODE_PRIVATE).getPath();
        //设置定位的数据库路径
        setting.setGeolocationDatabasePath(dir);

        wv_chart.loadUrl("file:///android_asset/echarts.html");

        wv_chart.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                getPerfromanceChart(perjson_month, "1");
            }
        });
        return wv_chart;
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tvNavBack:
                back();
                break;
            case R.id.tv_yifeng:
                showPopupWindow(tv_yifeng);
                break;
            case R.id.tv_buy:
                if (!UserTokenUtil.isOpenAccount(this)) {
                    ToastUtils.showShortToast(this, "请先开户");
                    Intent intent = new Intent(this, OpenAccountActivity.class);
                    startActivity(intent);
                    return;
                }
                MyAlertDialog alertDialog = new MyAlertDialog(GroupDetailActivity.this, "您将使用奕丰金融提供的基金销售服务", new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Intent intent = new Intent(GroupDetailActivity.this, GroupBuyActivity.class);
                        Bundle bundle = new Bundle();
                        bundle.putSerializable("entity", mGroup);
                        intent.putExtras(bundle);
                        startActivity(intent);
                    }
                });
                alertDialog.show();
                break;
        }
    }

    @Override
    public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
        switch (checkedId) {
            case R.id.radio1:
                getPerfromanceChart(perjson_month, "1");
                break;
            case R.id.radio2:
                getPerfromanceChart(perjson_3month, "2");
                break;
            case R.id.radio3:
                getPerfromanceChart(perjson_6month, "3");
                break;
            case R.id.radio4:
                getPerfromanceChart(perjson_year, "4");
                break;
        }
    }
}
